<template>
  <div class="vocabulary-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/english" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">生词本</h5>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar d-flex align-items-center">
      <i class="bi bi-search me-2"></i>
      <input 
        v-model="searchQuery" 
        type="text" 
        class="form-control border-0 bg-transparent" 
        placeholder="搜索单词..."
      >
    </div>

    <!-- 统计卡片 -->
    <div class="stats-card">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <h6 class="mb-1">今日新增</h6>
          <h3 class="mb-0">{{ stats.today }}个</h3>
        </div>
        <div>
          <h6 class="mb-1">总计单词</h6>
          <h3 class="mb-0">{{ stats.total }}个</h3>
        </div>
        <div>
          <h6 class="mb-1">已掌握</h6>
          <h3 class="mb-0">{{ stats.mastered }}个</h3>
        </div>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <div class="d-flex justify-content-between">
        <div class="btn-group">
          <button 
            v-for="filter in filters" 
            :key="filter.value"
            class="btn btn-outline-secondary"
            :class="{ active: currentFilter === filter.value }"
            @click="currentFilter = filter.value"
          >
            {{ filter.label }}
          </button>
        </div>
<!--        <div class="dropdown">-->
<!--          <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">-->
<!--            来源-->
<!--          </button>-->
<!--          <ul class="dropdown-menu">-->
<!--            <li v-for="source in sources" :key="source">-->
<!--              <a class="dropdown-item" href="#" @click="filterBySource(source)">{{ source }}</a>-->
<!--            </li>-->
<!--          </ul>-->
<!--        </div>-->
      </div>
    </div>

    <!-- 单词列表 -->
    <div class="word-list">
      <div v-for="word in filteredWords" :key="word.id" class="word-card">
        <div class="word-header">
          <div>
            <div class="word-text">{{ word.text }}</div>
            <div class="phonetic">{{ word.phonetic }}</div>
          </div>
          <div class="d-flex gap-2">
            <button class="btn btn-outline-primary btn-sm" @click="playPronunciation(word)">
              <i class="bi bi-volume-up"></i>
            </button>
            <button
              class="btn btn-outline-success btn-sm mastered-btn"
              :class="{ mastered: word.mastered }"
              @click="toggleMastered(word)"
            >
              <i class="bi bi-check-lg"></i>
            </button>
          </div>
        </div>
        <div class="meaning">{{ word.meaning }}</div>
        <div v-if="word.example" class="example">
          {{ word.example.en }}
          <div class="text-muted mt-1">{{ word.example.zh }}</div>
        </div>
        <div class="word-source">
          <i class="bi bi-bookmark"></i>
          来自：{{ word.source }}
        </div>
      </div>
    </div>

    <!-- 添加单词模态框 -->
    <div class="modal fade" id="addWordModal" tabindex="-1">
      <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">添加生词</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
            <form @submit.prevent="addNewWord">
              <div class="mb-3">
                <input
                  v-model="newWord"
                  type="text"
                  class="form-control form-control-lg"
                  placeholder="输入单词..."
                  required
                  autocomplete="off"
                >
              </div>
              <div class="text-muted small">
                <i class="bi bi-info-circle"></i>
                系统会自动获取单词的释义、音标等信息
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="addNewWord">添加</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 悬浮添加按钮 -->
    <button class="floating-btn border-0" data-bs-toggle="modal" data-bs-target="#addWordModal">
      <i class="bi bi-plus-lg fs-4"></i>
    </button>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { Modal } from 'bootstrap'
import http from "@/router/http";
import { nextTick } from 'vue';
import router from "@/router";
import {getTranslationInfo, getTranslationParaGraphInfo,getTranslationArticleInfo} from '@/services/BaiduTranslationService';
import dayjs from "dayjs";
import axios from 'axios';
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*'; // 尝试设置允许所有源跨域访问，实际应用中最好指定具体的前端域名
axios.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
axios.defaults.headers.common['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';

export default {
  name: 'VocabularyView',
  mounted() {
    this.feedWords();
  },
  setup() {
    const searchQuery = ref('')
    const currentFilter = ref('all')
    const newWord = ref('')

    const stats = ref({
      today: 0,
      total: 0,
      mastered: 0
    })

    const filters = [
      { label: '全部', value: 'all' },
      { label: '未掌握', value: 'unmastered' },
      { label: '已掌握', value: 'mastered' }
    ]

    const sources = ['阅读文章', '完形填空', '翻译']

    const words = ref([
      // ... 可以添加更多单词
    ])

    const filteredWords = computed(() => {
      let result = words.value

      // 搜索过滤
      if (searchQuery.value) {
        result = result.filter(word =>
          word.text.toLowerCase().includes(searchQuery.value.toLowerCase())
        )
      }

      // 掌握状态过滤
      if (currentFilter.value === 'mastered') {
        result = result.filter(word => word.mastered)
      } else if (currentFilter.value === 'unmastered') {
        result = result.filter(word => !word.mastered)
      }

      return result
    })

    const toggleMastered = (word) => {
      word.mastered = !word.mastered
      setMastered(word.id,word.mastered ? '已掌握' : '未掌握')
      showToast(word.mastered ? '已标记为掌握！' : '已取消掌握标记')
      location.reload();
    }

    const showToast = (message) => {
      // 这里可以使用第三方toast库或自定义实现
      alert(message) // 临时使用alert
    }

    const addNewWord = async () => {
      if (!newWord.value) {
        showToast('请输入单词');
        return;
      }
      try {
        // 调用异步函数获取单词信息，使用await等待其返回结果
        const data = await getTranslationInfo(newWord.value);
        let exampleCn = '';
        if (data && data.example && data.example!== '') {
          // 同样使用await等待获取例句中文翻译信息的异步函数返回结果
          exampleCn = (await getTranslationArticleInfo(data.example)).meaning || '';
        }
        const exampleInfo = [];
        if (data.example) {
          exampleInfo.push(data.example);
        }
        if (exampleCn) {
          exampleInfo.push(exampleCn);
        }

        // 构造要发送给后端的单词对象
        const word = {
          newWord: newWord.value,
          phoneticSymbol: data.pronunciationStr || '',
          translate: data.meaning || '未找到释义',
          audio: data.audio || '',
          sentenceTranslate: exampleInfo
        };

        // 发送POST请求到后端，使用await等待请求完成并获取响应结果
        const response = await http.post('/student/vocabularyList/addOrDelete?type=1', word);
        // 只有当请求成功返回后，才执行下面的操作

        words.value.unshift(word);
        await nextTick(); // 等待DOM更新完成
        showToast('添加新单词成功！');
        location.reload();
      } catch (error) {
        // 如果在上述任何一个异步操作（获取信息、发送请求等）中出现错误，在这里进行统一的错误处理
        console.error('添加新单词出现错误:', error);
        showToast('添加新单词失败，请稍后再试');
      }finally {
        newWord.value = '';
      }
    }

    const playPronunciation = (word) => {
      try {
        if (word.audio) {
          // 使用axios获取音频数据
          axios.get(word.audio, {
            responseType: 'arraybuffer' , // 设置响应类型为arraybuffer，用于处理二进制数据
            headers: {
              // 设置跨域请求头，*表示允许所有源访问，实际应用中最好指定具体的前端域名
              'Access-Control-Allow-Origin': '*',
              // 允许的请求方法
              'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
              // 允许的请求头
              'Access-Control-Allow-Headers': 'Content-Type, Authorization'
            }
          }).then(response => {
            // 将获取到的音频数据转换为Blob对象
            const audioBlob = new Blob([response.data], { type: 'audio/mpeg' });
            // 创建一个可播放的音频对象
            const audio = new Audio(URL.createObjectURL(audioBlob));
            audio.addEventListener('error', (event) => {
              console.error('音频播放出错，可能原因如下：');
              // 错误处理逻辑与之前类似
              if (event.target.error.code === event.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED) {
                console.error('音频格式不被支持，请确保音频格式为通用格式（如.mp3等）');
              } else if (event.target.error.code === event.target.error.MEDIA_ERR_NETWORK) {
                console.error('网络连接可能存在问题，请检查网络是否正常');
              } else if (event.target.error.code === event.target.error.MEDIA_ERR_DECODE) {
                console.error('音频解码出现故障，可能音频文件本身有损坏');
              } else {
                console.error('很可能存在跨域问题，外站音频需配置正确的跨域设置，可尝试以下操作：');
                console.error('1. 检查外站音频所在服务器是否允许跨域访问（可联系外站管理员）；');
                console.error('2. 查看浏览器是否限制了跨域资源加载，部分浏览器可通过设置安全策略来允许特定跨域访问，但需谨慎操作；');
                console.error('3. 尝试在前端代码中设置请求头（如已在代码中有相关设置，检查是否正确）。');
              }
              showToast('无法播放该单词发音，请检查上述问题');
              event.preventDefault();
            });
            audio.play();
          }).catch(error => {
            console.error('获取音频数据时出错：', error);
            showToast('获取音频资源失败，请稍后再试');
          });
        } else {
          showToast('音频资源不存在');
        }
      } catch (error) {
        console.error('音频播放出现其他未知错误：', error);
        showToast('播放音频时出现未知错误，请稍后再试');
      }
    };

    const filterBySource = (source) => {
      console.log('Filtering by source:', source)
      // 实现按来源筛选
    }
    const todyAdd = ref(0)
    const totalNum = ref(0)
    const masteredNum = ref(0)
    //请求后端接口
    const feedWords = async () => {
      const response = await http.get('/student/vocabularyList/select').then(response => {
        if(response.status === 200) {
          const data = response.data.response;
          todyAdd.value = 0;
          totalNum.value = 0;
          masteredNum.value = 0;
          data.forEach(item => {
            totalNum.value++;
            if(item.situation === '已掌握'){
              masteredNum.value++;
            }
            if(dayjs().isSame(dayjs(item.addTime), 'day')){
              todyAdd.value++;
            }
            words.value.push({
              id: item.vocabularyId,
              text: item.newWord,
              phonetic: item.phoneticSymbol,
              meaning: item.translate,
              audio: item.audio,
              example: {
                en: item.sentenceTranslate !== null && item.sentenceTranslate[0] !== null ? item.sentenceTranslate[0] : '',
                zh: item.sentenceTranslate !== null && item.sentenceTranslate[1] !== null ? item.sentenceTranslate[1] : ''
              },
              source: item.source,
              mastered: item.situation === '未掌握'? false : true
            });

          });
        }
      }).catch(error => {
        console.error('获取单词列表出错:', error);
        // 可以在这里进行一些错误提示相关处理，比如通过 showToast 函数显示错误消息给用户
        showToast('获取单词列表失败，请稍后再试');
      });
      stats.value = {
          today: todyAdd.value,
          total: totalNum.value,
          mastered: masteredNum.value
        }

    }
    //标记掌握
    const setMastered = async (id,type) => {
      const params = {
        vocabularyId: id,
        situation: type
      }
      const response = await http.post('/student/vocabularyList/update', params).then(response => {
      }).catch(error => {
        console.error('修改掌握状态异常:', error);
      });

    }
    return {
      searchQuery,
      currentFilter,
      newWord,
      stats,
      filters,
      sources,
      words,
      filteredWords,
      toggleMastered,
      addNewWord,
      playPronunciation,
      filterBySource,
      feedWords
    }
  }
}
</script>

<style scoped>
body {
  background-color: #f0f9f9;
  padding-bottom: 60px;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.search-bar {
  background: #f5f5f5;
  border-radius: 20px;
  padding: 8px 15px;
  margin: 10px 15px;
}

.word-card {
  background: white;
  border-radius: 15px;
  padding: 20px;
  margin: 15px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.word-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.word-text {
  font-size: 1.2rem;
  font-weight: bold;
}

.phonetic {
  color: #666;
  font-size: 0.9rem;
}

.meaning {
  color: #333;
  margin: 10px 0;
}

.example {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  margin: 10px 0;
  font-size: 0.95rem;
}

.word-source {
  color: #666;
  font-size: 0.85rem;
}

.stats-card {
  background: linear-gradient(45deg, #00b8a9, #20d6c7);
  color: white;
  border-radius: 15px;
  padding: 15px;
  margin: 15px;
}

.floating-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  border-radius: 25px;
  background: #00b8a9;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.mastered-btn {
  background-color: white;
  border: 1px solid #198754;
  color: #198754;
}

.mastered-btn.mastered {
  background-color: #198754;
  color: white;
}

.filter-bar {
  padding: 10px 15px;
  background: white;
  position: sticky;
  top: 56px;
  z-index: 999;
}

.form-control-lg {
  font-size: 1.2rem;
  padding: 12px 15px;
  border-radius: 10px;
}

.form-control-lg:focus {
  border-color: #00b8a9;
  box-shadow: 0 0 0 0.25rem rgba(0, 184, 169, 0.25);
}
</style> 